<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Models\Recharge;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Log;

class RechargeController extends Controller
{
    /**
     * 获取充值列表
     */
    public function index(Request $request): JsonResponse
    {
        try {
            // 获取租户ID
            $tenantId = $request->user()->tenant_id;
            
            Log::info('充值列表请求', [
                'tenant_id' => $tenantId,
                'params' => $request->all()
            ]);
            
            // 构建查询
            $query = Recharge::where('tenant_id', $tenantId);
            
            // 搜索条件
            if ($request->filled('recharge_id')) {
                $rechargeId = trim($request->input('recharge_id'));
                $query->where(function($q) use ($rechargeId) {
                    $q->where('recharge_number', 'like', "%{$rechargeId}%")
                      ->orWhere('id', 'like', "%{$rechargeId}%");
                });
            }
            
            if ($request->filled('status')) {
                $query->where('status', $request->input('status'));
            }
            
            if ($request->filled('landing_company')) {
                $landingCompany = trim($request->input('landing_company'));
                $query->where('landing_company', 'like', "%{$landingCompany}%");
            }
            
            // 创建时间范围
            if ($request->filled('start_date') && $request->filled('end_date')) {
                $startDate = $request->input('start_date') . ' 00:00:00';
                $endDate = $request->input('end_date') . ' 23:59:59';
                $query->whereBetween('created_at', [$startDate, $endDate]);
            }
            
            // 排序
            $sortBy = $request->input('sort_by', 'created_at');
            $sortOrder = $request->input('sort_order', 'desc');
            $query->orderBy($sortBy, $sortOrder);
            
            // 分页
            $perPage = (int) $request->input('per_page', 15);
            $perPage = min($perPage, 100); // 限制每页最大100条
            
            $recharges = $query->paginate($perPage);
            
            // 处理数据
            $processedData = $recharges->getCollection()->map(function ($recharge) {
                return [
                    'id' => $recharge->id,
                    'recharge_id' => $recharge->recharge_id,
                    'recharge_number' => $recharge->recharge_number,
                    'tenant_id' => $recharge->tenant_id,
                    'landing_company' => $recharge->landing_company,
                    'amount' => $recharge->amount,
                    'bank_name' => $recharge->bank_name,
                    'bank_account' => $recharge->bank_account,
                    'status' => $recharge->status,
                    'status_display' => $recharge->status_display,
                    'status_description' => $recharge->status_description,
                    'remarks' => $recharge->remarks,
                    'created_at' => $recharge->created_at,
                    'updated_at' => $recharge->updated_at,
                    'arrived_at' => $recharge->arrived_at,
                    'settled_at' => $recharge->settled_at,
                    'refunded_at' => $recharge->refunded_at,
                    'created_by' => $recharge->created_by,
                    'updated_by' => $recharge->updated_by,
                ];
            });
            
            $result = [
                'data' => $processedData,
                'current_page' => $recharges->currentPage(),
                'per_page' => $recharges->perPage(),
                'total' => $recharges->total(),
                'last_page' => $recharges->lastPage(),
                'from' => $recharges->firstItem(),
                'to' => $recharges->lastItem(),
                'first_page_url' => $recharges->url(1),
                'last_page_url' => $recharges->url($recharges->lastPage()),
                'next_page_url' => $recharges->nextPageUrl(),
                'prev_page_url' => $recharges->previousPageUrl(),
                'path' => $recharges->path(),
                'links' => $recharges->linkCollection()->toArray()
            ];
            
            Log::info('充值列表查询成功', [
                'tenant_id' => $tenantId,
                'total' => $recharges->total(),
                'current_page' => $recharges->currentPage()
            ]);
            
            return response()->json([
                'code' => 0,
                'data' => $result,
                'message' => '获取充值列表成功'
            ]);
            
        } catch (\Exception $e) {
            Log::error('充值列表查询失败', [
                'tenant_id' => $request->attributes->get('tenant_id'),
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return response()->json([
                'success' => false,
                'data' => null,
                'message' => '获取充值列表失败',
                'error' => [
                    'details' => $e->getMessage()
                ]
            ], 500);
        }
    }

    /**
     * 创建充值记录
     */
    public function store(Request $request): JsonResponse
    {
        try {
            // 获取租户ID
            $tenantId = $request->user()->tenant_id;
            
            Log::info('创建充值请求', [
                'tenant_id' => $tenantId,
                'params' => $request->all()
            ]);
            
            // 验证请求数据
            $validated = $request->validate([
                'landing_company' => 'required|string|max:200',
                'amount' => 'required|numeric|min:0.01|max:999999999.99',
                'bank_name' => 'required|string|max:100',
                'bank_account' => 'required|string|max:50',
                'remarks' => 'nullable|string|max:1000'
            ], [
                'landing_company.required' => '落地公司不能为空',
                'landing_company.max' => '落地公司名称不能超过200个字符',
                'amount.required' => '充值金额不能为空',
                'amount.numeric' => '充值金额必须是数字',
                'amount.min' => '充值金额必须大于0.01元',
                'amount.max' => '充值金额不能超过999,999,999.99元',
                'bank_name.required' => '银行名称不能为空',
                'bank_name.max' => '银行名称不能超过100个字符',
                'bank_account.required' => '银行账号不能为空',
                'bank_account.max' => '银行账号不能超过50个字符',
                'remarks.max' => '备注不能超过1000个字符'
            ]);
            
            // 创建充值记录
            $recharge = Recharge::create([
                'tenant_id' => $tenantId,
                'landing_company' => $validated['landing_company'],
                'amount' => $validated['amount'],
                'bank_name' => $validated['bank_name'],
                'bank_account' => $validated['bank_account'],
                'remarks' => $validated['remarks'] ?? null,
                'status' => Recharge::STATUS_PENDING,
                'created_by' => $request->attributes->get('user_id', 1)
            ]);
            
            Log::info('充值记录创建成功', [
                'tenant_id' => $tenantId,
                'recharge_id' => $recharge->id,
                'recharge_number' => $recharge->recharge_number,
                'amount' => $recharge->amount
            ]);
            
            return response()->json([
                'code' => 0,
                'data' => [
                    'id' => $recharge->id,
                    'recharge_id' => $recharge->recharge_id,
                    'recharge_number' => $recharge->recharge_number,
                    'tenant_id' => $recharge->tenant_id,
                    'landing_company' => $recharge->landing_company,
                    'amount' => $recharge->amount,
                    'bank_name' => $recharge->bank_name,
                    'bank_account' => $recharge->bank_account,
                    'status' => $recharge->status,
                    'status_display' => $recharge->status_display,
                    'remarks' => $recharge->remarks,
                    'created_at' => $recharge->created_at,
                ],
                'message' => '充值记录创建成功'
            ], 201);
            
        } catch (\Illuminate\Validation\ValidationException $e) {
            Log::warning('充值创建验证失败', [
                'tenant_id' => $request->attributes->get('tenant_id'),
                'errors' => $e->errors()
            ]);
            
            return response()->json([
                'success' => false,
                'data' => null,
                'message' => '数据验证失败',
                'errors' => $e->errors()
            ], 422);
            
        } catch (\Exception $e) {
            Log::error('充值记录创建失败', [
                'tenant_id' => $request->attributes->get('tenant_id'),
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return response()->json([
                'success' => false,
                'data' => null,
                'message' => '创建充值记录失败',
                'error' => [
                    'details' => $e->getMessage()
                ]
            ], 500);
        }
    }

    /**
     * 获取充值详情
     */
    public function show(Request $request, $id): JsonResponse
    {
        try {
            $tenantId = $request->user()->tenant_id;
            
            $recharge = Recharge::where('tenant_id', $tenantId)->where('id', $id)->first();
            
            if (!$recharge) {
                return response()->json([
                    'success' => false,
                    'data' => null,
                    'message' => '充值记录不存在或无权访问'
                ], 404);
            }
            
            return response()->json([
                'code' => 0,
                'data' => [
                    'id' => $recharge->id,
                    'recharge_id' => $recharge->recharge_id,
                    'recharge_number' => $recharge->recharge_number,
                    'tenant_id' => $recharge->tenant_id,
                    'landing_company' => $recharge->landing_company,
                    'amount' => $recharge->amount,
                    'bank_name' => $recharge->bank_name,
                    'bank_account' => $recharge->bank_account,
                    'status' => $recharge->status,
                    'status_display' => $recharge->status_display,
                    'status_description' => $recharge->status_description,
                    'remarks' => $recharge->remarks,
                    'created_at' => $recharge->created_at,
                    'updated_at' => $recharge->updated_at,
                    'arrived_at' => $recharge->arrived_at,
                    'settled_at' => $recharge->settled_at,
                    'refunded_at' => $recharge->refunded_at,
                ],
                'message' => '获取充值详情成功'
            ]);
            
        } catch (\Exception $e) {
            Log::error('获取充值详情失败', [
                'id' => $id,
                'tenant_id' => $request->attributes->get('tenant_id'),
                'error' => $e->getMessage()
            ]);
            
            return response()->json([
                'success' => false,
                'data' => null,
                'message' => '获取充值详情失败'
            ], 500);
        }
    }

    /**
     * 导出充值数据为CSV
     */
    public function export(Request $request): JsonResponse
    {
        try {
            // 获取租户ID
            $tenantId = $request->user()->tenant_id;
            
            // 构建查询（与index方法相同的逻辑）
            $query = Recharge::where('tenant_id', $tenantId);
            
            // 应用搜索条件
            if ($request->filled('recharge_id')) {
                $rechargeId = trim($request->input('recharge_id'));
                $query->where(function($q) use ($rechargeId) {
                    $q->where('recharge_number', 'like', "%{$rechargeId}%")
                      ->orWhere('id', 'like', "%{$rechargeId}%");
                });
            }
            
            if ($request->filled('status')) {
                $query->where('status', $request->input('status'));
            }
            
            if ($request->filled('landing_company')) {
                $landingCompany = trim($request->input('landing_company'));
                $query->where('landing_company', 'like', "%{$landingCompany}%");
            }
            
            if ($request->filled('start_date') && $request->filled('end_date')) {
                $startDate = $request->input('start_date') . ' 00:00:00';
                $endDate = $request->input('end_date') . ' 23:59:59';
                $query->whereBetween('created_at', [$startDate, $endDate]);
            }
            
            // 排序
            $query->orderBy('created_at', 'desc');
            
            // 获取所有数据（用于导出，不分页）
            $recharges = $query->get();
            
            Log::info('充值数据导出', [
                'tenant_id' => $tenantId,
                'count' => $recharges->count()
            ]);
            
            return response()->json([
                'code' => 0,
                'data' => [
                    'count' => $recharges->count(),
                    'export_url' => '/api/tenant/recharges/download-csv?' . http_build_query($request->all())
                ],
                'message' => '导出数据准备完成'
            ]);
            
        } catch (\Exception $e) {
            Log::error('充值数据导出失败', [
                'tenant_id' => $request->attributes->get('tenant_id'),
                'error' => $e->getMessage()
            ]);
            
            return response()->json([
                'success' => false,
                'data' => null,
                'message' => '导出数据失败'
            ], 500);
        }
    }
}